package com.cy.shiro;

import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台管理登录验证的拦截器
 */
public class AdminAuthorizationFilter extends AuthorizationFilter {
    /**
     * 仅验证该用户是否已经登录
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        return subject.isAuthenticated();
    }

    /**
     * 拒绝访问跳转
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String requestType = req.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(requestType)){//AJAX请求
            Map<String, Object> result = new HashMap<>();
            result.put("status", EnumConst.RetCode.NOT_SIGNIN.getCode());
            result.put("msg", EnumConst.RetCode.NOT_SIGNIN.getValue());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(result));
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}
